<?php


namespace Api\Controller;

/*
 * 抽奖控制器
 * */
class LotteryController extends BaseController
{
    private $_checkLotteryTime = false;
    /* 获取奖品以及抽奖配置信息 */
    public function getPrizeInfo(){
        $userId = I('userId','');
        if(!$userId){
            exit(json_encode(
                [
                    'result' => 401,
                    'message' => '无法获取用户id',
                ]
            ));
        }
        /* 奖品信息 */
        $lotteryPrize = M('LotteryPrize');
        $prizeInfo = $lotteryPrize  -> field('prize_id,prize_name,prize_num,prize_img,prize_sort,prize_status')
                                    -> order('prize_sort asc')
                                    -> select();
        /* 抽奖配置信息 */
        $lotteryConfig = M('LotteryConfig');
        $configInfo = $lotteryConfig -> field('id,name,key,value') -> select();
        $configInfo = array_combine(array_column($configInfo,'key'),$configInfo);
        /* 近期获奖用户 */
        $lotteryRecord = M('LotteryRecord');
        $recordInfo = $lotteryRecord -> join('ln_users ON ln_users.user_id = ln_lottery_record.user_id')
                       -> join('ln_lottery_prize On ln_lottery_prize.prize_id = ln_lottery_record.prize_id')
                       -> field('nickname,ln_lottery_record.user_id,ln_lottery_record.create_time,mobile,prize_name')
                       -> where('category_id != 0')
                       -> order('ln_lottery_record.create_time asc')
                       -> limit('10')
                       -> select();
        /* 用户抽象情况 */
        $t = time();
        $start_time = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));  //当天开始时间
        $end_time = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t)); //当天结束时间
//        $where = 'user_id = '.$userId." and create_time < ".$start_time." and create_time > ".$end_time;
        $where['user_id'] = $userId;
        $where[]['create_time'] = ['gt',$start_time];
        $where[]['create_time'] = ['lt',$end_time];
        $userLotteryCount = $lotteryRecord -> field('count(id) as num') -> where($where) -> find();
        exit(json_encode(
            [
                'result' => 200,
                'message' => '获取抽奖信息成功',
                'data' => [
                    'prizeInfo' => $prizeInfo,
                    'configInfo' => $configInfo,
                    'recordInfo' => $recordInfo,
                    'userLotteryCount' => $userLotteryCount
                ]
            ]
        ));
    }

    /* 用户抽奖 */
    public function lotteryDraw(){
        /* 获取用户id */
        $userId = I('userId','');
        /* 验证用户id非空 */
        if(!$userId){
            exit(json_encode(['result' => 401,'message' => '无法获取用户id']));
        }
        $data['user_id'] = $userId;
        if($this -> _checkLotteryTime){
            $lotteryTime = $this -> checkLotteryTime();
            if(!$lotteryTime){
                exit(json_encode(['result' => 402,'message' => '抽奖活动未开始']));
            }
        }
        /* 验证用户是否满足抽奖条件 */
        $userStatus = $this -> checkUserLotteryStatus($userId);
        if(!$userStatus){
            exit(json_encode(['result' => 403,'message' => '不满足抽奖条件']));
        }
        /* 验证用户抽奖次数 */
        $lotteryNum = $this -> checkUserLotteryNum($userId);
        if(!$lotteryNum){
            exit(json_encode(['result' => 404,'message' => '今日抽奖次数到达上限']));
        }
        /* 随机奖品id */
        $prizeInfo = $this -> getPrizeId();
        if(!$prizeInfo){
            exit(json_encode(['result' => 405,'message' => '奖品数量不足']));
        }
        /* 添加抽奖记录 */
        $data['create_time'] = time();
        $data['prize_id'] = $prizeInfo['prize_id'];
        $lotteryRecord = M('LotteryRecord');
        $insert_id = $lotteryRecord -> add($data);
        if($insert_id){
            /* 奖品需要验证数量，抽奖完成奖品数量-1 */
            if($prizeInfo['check_num'] == 1){
                $this -> updatePrizeNum($prizeInfo['prize_id']);
            }
            /* 抽奖完成后，扣除优惠券总额 */
            $this -> deductCouponPrice($userId);
            exit(json_encode(['result' => 200,'message' => '抽奖完成','data' => $prizeInfo]));
        }
    }

    /* 验证抽奖活动是否开始 */
    protected function checkLotteryTime(){
        $nowTime = time();
        /* 获取抽奖配置限制 */
        $startTime = M('LotteryConfig') -> field('value') -> where("`key` = 'lotteryStartTime'") -> find();
        $endTime = M('LotteryConfig') -> field('value') -> where("`key` = 'lotteryEndTime' ") -> find();
        if($nowTime < $startTime['value'] || $nowTime > $endTime['value']){
            return false;
        }else{
            return true;
        }
    }

    /* 扣除优惠券总额 */
    protected function deductCouponPrice($userId){
        /* 获取抽奖配置限制 */
        $lotteryConsume = M('LotteryConfig')
                        -> field('value')
                        -> where("`key` = 'lotteryConsume'")
                        -> find();
        /* 获取用户所有优惠券 */
        $where['uid'] = $userId;
        $where['status'] = 1;
        $couponList = M('CouponList')
                    -> join('ln_coupon ON ln_coupon.id = ln_coupon_list.cid')
                    -> field('ln_coupon.money,ln_coupon_list.id')
                    -> where($where)
                    -> order('use_end_time asc')
                    -> select();
        $i = 0;
        $price = 0;
        $data = [];
        while ($price < $lotteryConsume['value']){
            $price = $this -> mathAdd($price,$couponList[$i]['money']);
            array_push($data,$couponList[$i]['id']);
            unset($couponList[$i]);
            $i++;
        }
        $str = implode($data,',');
        $couponTotalPrice = array_sum(array_column($couponList,'money'));
        /* 修改用户优惠劵总价 */
        $lotteryPrize = M('users')
            -> where('user_id='.$userId)
            -> save(['coupon_price' => $couponTotalPrice]);
        /* 修改用户优惠券状态 */
        $couponListRes = M('CouponList')
                        -> where('id in ('.$str.')')
                        -> save(['status' => 0]);
    }

    /* 验证用户抽奖条件 */
    protected function checkUserLotteryStatus($userId){
        /* 获取抽奖配置限制 */
        $lotteryConsume = M('LotteryConfig') -> field('value') -> where("`key` = 'lotteryConsume'") -> find();
        /* 获取用户优惠券总额 */
        $couponPrice = M('users') -> field('coupon_price') -> where("`user_id` = ".$userId) -> find();
        return $couponPrice['coupon_price'] < $lotteryConsume['value'] ? false : true;
    }

    /* 验证用户抽奖次数 */
    protected function checkUserLotteryNum($userId){
        /* 获取抽奖配置次数 */
        $lotteryNum = M('LotteryConfig') -> field('value') -> where("`key` = 'lotteryNum'") -> find();
        /* 获取用户抽奖次数 */
        $t = time();
        $start_time = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));  //当天开始时间
        $end_time = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t)); //当天结束时间
        $where['user_id'] = $userId;
        $where['create_time'] = ['gt',$start_time];
        $where['create_time'] = ['lt',$end_time];
        $userNum = M('LotteryRecord') -> field('count(id) as num') -> where($where) -> find();
        return $lotteryNum['value'] == $userNum['num'] ? false : true;
    }

    /* 奖品数量-1 */
    protected function updatePrizeNum($prize_id){
        $lotteryPrize = M('LotteryPrize')
            -> where('prize_id='.$prize_id)
            -> setDec('prize_num');
    }

    /* 随机抽奖id */
    protected function getPrizeId(){
        $lotteryPrize = M('LotteryPrize')
                        -> field('prize_id,prize_weight,prize_name,prize_img,prize_num,check_num')
                        -> select();
        //下标存储数组100个下表，0-7 按概率分配对应的数量
        $indexArr = array();
        for($i=0;$i<sizeof($lotteryPrize);$i++){
            for($j=0;$j<$lotteryPrize[$i]['prize_weight'];$j++){
                //index 追加到数组indexArr
                array_push($indexArr, $i);
            }
        }
        //数组乱序
        shuffle($indexArr);
        //从下标数组中随机取一个下标作为中奖下标，$rand_index 是$indexArr的随机元素的下标（0-99）
        $rand_index = array_rand($indexArr,1);
        //获取中奖信息
        $prize_index = $indexArr[$rand_index];
        $prizeInfo = $lotteryPrize[$prize_index];
        $data['prize_id'] = $prizeInfo['prize_id'];
        $data['prize_name'] = $prizeInfo['prize_name'];
        $data['prize_img'] = $prizeInfo['prize_img'];
        $data['prize_num'] = $prizeInfo['prize_num'];
        $data['check_num'] = $prizeInfo['check_num'];
        if($data['check_num'] == 1 && $data['prize_num'] == 0){
            return false;
        }else{
            return $data;
        }
    }

    /* 获取用户获奖记录 */
    public function getUserRecord(){
        $userId = I('post.userId','');
        if(!$userId){
            exit(['result' => 401,'message' => '参数有误']);
        }
        /* 近期获奖用户 */
        $lotteryRecord = M('LotteryRecord');
        $userRecordData = $lotteryRecord -> join('ln_lottery_prize On ln_lottery_prize.prize_id = ln_lottery_record.prize_id')
            -> field('prize_name,prize_img,ln_lottery_record.create_time')
            -> where(['user_id' => $userId,'category_id' => ['NEQ',0]])
            -> order('ln_lottery_record.create_time asc')
            -> limit('10')
            -> select();
        exit(json_encode([
            'result' => 200,
            'message' => '获取用户记录成功',
            'data' => $userRecordData
        ]));
    }

    /* 加 */
    public function mathAdd($a,$b,$scale = '2'){
        return bcadd($a,$b,$scale);
    }
}